
import { defineStore } from 'pinia'

import { ListShopCartService } from '@/api/shopcart'

// 用于存放用户相关信息
export const useUser = defineStore("userInfo", {
  state: () => {
    return {
      // 是否显示登录界面
      showLogin: false,
      // 用户信息
      user: {
        user_id: '',
        userName: '',
        userAddress: ''
      }
    }
  },
  actions: {
    // 修改登录状态
    setShowLogin(flag) {
      this.showLogin = flag
    },
    // 设置用户信息
    setUser(val) {
      this.user.user_id = val.userId
      this.user.userName = val.username
      this.user.userAddress = val.address
    },
    // 重置用户信息
    reset() {
      this.user.user_id = '';
      this.user.userName = ''
      this.user.userAddress = ''
    }
  }

})

// 用于存放购物车相关信息
export const useShopcart = defineStore('shopcart', {
  state: () => {
    return {
      // 登录用户的购物车数组
      shopcartList: []
    }
  },
  actions: {
    // 加载购物车信息
    async loadShopcartList() {
      let userStore = useUser()
      const userId = userStore.user.user_id
      // 没有进行登录
      if (!userId) return
      
      const { data } = await ListShopCartService(userId)
      if (data.success) {
        this.shopcartList = data.data.map(r => {
          return {
            ...r,
            // 添加状态  -->  默认当前商品是为选中的状态
            state: true
          }
        })
      }
    },
    // 获取单个购物车信息
    getShopcartOne(userId, goodsId) {
      return this.shopcartList.find(r => r.userId === userId && r.goodsId === goodsId)
    },
    // 删除本地购物车数据
    delShoppingCart(userId, goodsId) {
      let index = this.shopcartList.findIndex(r => r.userId === userId && r.goodsId === goodsId)
      this.shopcartList.splice(index, 1)
    },
    // 清空购物车
    clear() {
      this.shopcartList = []
    }
  }
})
